<?php

App::uses('AppController', 'Controller');

class PrevozniciController extends AppController {
	
	public $uses = array('Carrier', 'Vehicle', 'Driver');
	
	public function index() {
		$this->set('carriers', $this->Carrier->find('all'));
	}
	
	public function novi() {
		$this->set('carrier', $this->Carrier->create());
		$this->render('form');
	}
	
	public function izmeni($id) {
		$carrier = $this->Carrier->findById($id);
		if (! $carrier) {
			$this->redirect('index');
		}
		
		$this->set('carrier', $carrier);
		$this->render('form');
	}
	
	public function sacuvaj() {
		$data = @$this->data;
		if (! empty($data['Carrier'])) {
			$this->Carrier->set($data);
			
			if ($this->Carrier->validates()) {
				if ((int)$this->Carrier->id > 0) {
					$this->Vehicle->deleteAll(array( 'Vehicle.carrier_id' => (int)$this->Carrier->id));
					$this->Driver->deleteAll(array( 'Driver.carrier_id' => (int)$this->Carrier->id));
				}
				
				if ($this->Carrier->saveAll($data)) {
					$this->setFlash('Sačuvano.', 'ok');
					$this->redirect('/prevoznici/izmeni/' . $this->Carrier->id);
				} else {
					$this->setFlash('Čuvanje nije uspelo.');
					$this->set('carrier', $data);
					return $this->render('form');
				}
			} else {
				$this->setFlash('Uneti podaci nisu validni.');
				$this->set('carrier', $data);
				return $this->render('form');
			}
		}
		
		$this->redirect('index');
	}
	
	public function obrisi($id) {
		if ($id>0) {
			if ($this->Carrier->delete($id)) {
				$this->setFlash('Prevoznik je obrisan.', 'ok');
			} else {
				$this->setFlash('Brisanje nije uspelo.');
			}
		}
		$this->redirect('index');
	}
}
